<template>
  <view class="wrap">
    <view class="search">
      <uni-search-bar
        v-model="state.searchValue"
        @cancel="cancelSearch"
        @focus="state.searchFocus = true"
        @input="searchFood"
        @clear="
          () => {
            state.isSearch = false
            state.searchList = []
          }
        "
        placeholder="请搜索食物名称"
      />
    </view>
    <!-- 搜索内容 -->
    <view v-if="state.searchFocus" class="search_content">
      <view v-if="state.searchHistory.length > 0 && !state.isSearch" class="search_history">
        <view class="history_top">
          <view class="title">搜索记录</view>
          <icon type="" @tap="clearSearchHistory" class="iconfont icon-shanchu1 img_del" />
        </view>
        <view class="history_content">
          <view
            class="history_item"
            v-for="(item, index) in state.searchHistory"
            :key="index"
            @tap="historySelect(item)"
          >
            {{ item }}
          </view>
        </view>
      </view>
      <view v-if="state.searchList.length === 0 && state.isSearch" class="nodata">
        <image class="img_nodata" src="https://ainengli.hzjrsw.com/jkhx/noSearchData.png" />
        <view class="nodata_text">暂无数据，换个搜索条件试试?</view>
      </view>
      <view class="search_list">
        <view class="search_item" v-for="(item, index) in state.searchList" :key="index">
          <view class="name">{{ item.dietName }}</view>
          <view class="power">{{ item.energy }}千卡/100克</view>
          <image
            v-if="item.checked"
            class="img_right"
            src="https://ainengli.hzjrsw.com/jkhx/common/selected.png"
          />
          <image
            v-if="!item.checked"
            class="img_right"
            @tap="foodAdd(item, 'search')"
            src="https://ainengli.hzjrsw.com/jkhx/common/add.png"
          />
          <!-- <icon type="" v-if="item.checked" class="iconfont icon-xuanzhong-1 img_right"></icon>
                    <icon type="" v-if="!item.checked" @tap="foodAdd(item, 'search')" class="iconfont icon-zengjia1 img_right"></icon> -->
        </view>
      </view>
    </view>
    <!-- 加载状态 -->
    <up-loading-icon v-if="state.loading" text="" size="34" color="#00D1B6" />
    <!-- 食物列表 -->
    <view v-if="!state.searchFocus && !state.loading" class="content">
      <view class="left">
        <view
          :class="['item', state.active == index ? 'on' : '']"
          v-for="(item, index) in state.typeList"
          :key="index"
          @tap="typeSelect(index)"
        >
          <view v-if="state.active == index" class="line" />
          {{ item.name }}
        </view>
      </view>
      <scroll-view :scroll-top="scrollTop" @scroll="scrollTo" class="scroll-Y" scroll-y="true">
        <view class="right">
          <view class="item" v-for="(item, index) in state.detailList" :key="index">
            <view class="name">{{ item.dietName }}</view>
            <view class="power">{{ item.energy }}千卡/100克</view>
            <image
              v-if="item.checked"
              class="img_right"
              src="https://ainengli.hzjrsw.com/jkhx/common/selected.png"
            />
            <image
              v-if="!item.checked"
              class="img_right"
              @tap="foodAdd(item, 'list')"
              src="https://ainengli.hzjrsw.com/jkhx/common/add.png"
            />
            <!-- <icon type="" v-if="item.checked" class="iconfont icon-xuanzhong-1 img_right"></icon>
                        <icon type="" v-if="!item.checked" @tap="foodAdd(item, 'list')" class="iconfont icon-zengjia-1 img_right"></icon> -->
          </view>
        </view>
      </scroll-view>
    </view>
    <!-- 食物重量设置 -->
    <up-popup :show="state.setShow" :round="16" mode="bottom" closeable @close="close">
      <view class="food_info">
        <view class="title">
          {{ formatDate(state.date, 'MM月dd日') + ' ' + state.type }}
        </view>
        <view class="info_top">
          <view class="name">{{ state.addFood.dietName }}</view>
          <view class="power">{{ state.addFood.energy }}千卡/100克</view>
        </view>
        <view class="info_detail">
          <view class="detail_item">
            <view class="text">热量</view>
            <view>{{ (state.addFood.energy * (state.addFood.amount / 100)).toFixed(1) }}千卡</view>
          </view>
          <view class="detail_item">
            <view class="text">碳水化合物</view>
            <view>{{ (state.addFood.cho * (state.addFood.amount / 100)).toFixed(1) }}克</view>
          </view>
          <view class="detail_item">
            <view class="text">蛋白质</view>
            <view>{{ (state.addFood.pro * (state.addFood.amount / 100)).toFixed(1) }}克</view>
          </view>
          <view class="detail_item">
            <view class="text">脂肪</view>
            <view>{{ (state.addFood.fat * (state.addFood.amount / 100)).toFixed(1) }}克</view>
          </view>
        </view>
        <view class="input_info">
          <input
            type="digit"
            class="weight_input"
            :focus="state.tipFocus"
            :maxlength="4"
            @input="onInput"
            :adjustPosition="false"
            @keyboardheightchange="onKey"
            v-model="state.addFood.amount"
          />
          <view class="unit">克</view>
          <view class="hot"
            >(热量约{{
              (state.addFood.energy * (state.addFood.amount / 100)).toFixed(1)
            }}千卡)</view
          >
        </view>
        <button class="submit" @tap="foodSelect">确定</button>
        <view class="bottom_box" :style="{ height: `${state.bottomHeight}rpx` }" />
      </view>
    </up-popup>
    <!-- 固定底部 -->
    <view v-if="!state.setShow && !state.searchFocus" class="fixed">
      <view @tap="state.mealShow = !state.mealShow" class="fixed_left">
        <uni-badge
          :text="state.selected.length"
          absolute="rightTop"
          :offset="[2, 8]"
          size="small"
          :custom-style="{ background: '#F53F3F', fontSize: '24rpx' }"
        >
          <icon type="" class="iconfont icon-shiwu1 img_type" />
        </uni-badge>
        <text class="text">{{ state.type }}</text>
        <text type="" v-if="!state.mealShow" class="iconfont icon-jiantou img_arrow img_up" />
        <text type="" v-if="state.mealShow" class="iconfont icon-jiantou img_arrow" />
      </view>
      <button v-if="state.selected.length > 0" @tap="finish" class="fixed_btn">保存</button>
      <button v-if="state.selected.length == 0" class="fixed_btn disabled">保存</button>
    </view>
    <!-- 已选食物弹窗 -->
    <up-popup
      :show="state.mealShow"
      :round="16"
      mode="bottom"
      :customStyle="{ bottom: '112rpx' }"
      @close="state.mealShow = false"
    >
      <view class="total">
        共{{ state.selected.length }}条记录，总计{{ totalPower.toFixed(2) }}千卡
      </view>
      <view v-if="state.selected.length > 0" class="lists">
        <view v-for="(item, index) in state.selected" :key="index" class="item">
          <view class="name">{{ item.dietName }}</view>
          <view class="power">{{ (item.energy * item.amount) / 100 }}千卡/{{ item.amount }}克</view>
          <icon type="" @tap="deleteFood(item, index)" class="iconfont icon-shanchu1 img_del" />
        </view>
      </view>
    </up-popup>
  </view>
</template>
<script setup lang="ts">
import { reactive, ref, computed, nextTick } from 'vue'
import { query_all_food, query_get_food, save_food, search_food } from '@/module/api/food'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { debounce, throttle } from '@/utils/tools'
import { formatDate } from '@/utils/util'

const state = reactive({
  userInfo: {},
  searchFocus: false,
  isSearch: false,
  searchValue: '',
  searchHistory: [],
  searchList: [],
  typeList: [],
  detailList: [],
  active: 0,
  type: '',
  date: '',
  selected: [],
  addFood: {},
  addType: '',
  mealShow: false,
  setShow: false,
  tipFocus: false,
  loading: false,
  bottomHeight: 0
})
const scrollTop = ref(0)
const oldScrollTop = ref(0)

const totalPower = computed(() => {
  let sum = 0
  if (state.selected.length > 0) {
    state.selected.forEach((item) => {
      sum += (item.energy * item.amount) / 100
    })
  }
  return sum
})

onLoad((option) => {
  state.type = option.food ? option.food : ''
  state.date = option.date ? option.date : ''
})
onShow(() => {
  state.userInfo = uni.getStorageSync('userInfo')
    ? JSON.parse(uni.getStorageSync('userInfo')).patientInfo
    : {}
  state.searchHistory = uni.getStorageSync('searchHistory')
    ? JSON.parse(uni.getStorageSync('searchHistory'))
    : []
  getFoodDict()
})

const getFoodDict = () => {
  state.loading = true
  query_all_food().then((res) => {
    state.loading = false
    state.typeList = res.data
    state.typeList.forEach((i) => {
      i.list.forEach((j) => {
        j.checked = false
      })
    })
    state.detailList = state.typeList[state.active].list
    getData()
  })
}
const getData = () => {
  const params = {
    empi: state.userInfo.empi,
    date: state.date
  }
  query_get_food(params).then((res) => {
    // 赋值已选中的列表
    res.data.forEach((item) => {
      if (state.type == item.dietType) {
        state.selected = item.list
      }
    })
    state.detailList.forEach((item) => {
      // 如果已选中的列表没有为false, 有就为true
      item.checked = false
      state.selected.forEach((i) => {
        if (i.dietCode == item.dietCode) {
          item.checked = true
        }
      })
    })
  })
}
const cancelSearch = () => {
  state.searchFocus = false
  state.isSearch = false
  state.searchList = []
}
const clearSearchHistory = () => {
  state.searchHistory = []
  uni.removeStorageSync('searchHistory')
}
const searchFood = debounce((e) => {
  if (e == '') {
    state.isSearch = false
    state.searchList = []
    return
  }
  state.isSearch = true
  search_food(state.searchValue).then((res) => {
    state.searchList = res.data
    state.searchList.forEach((item) => {
      // 如果已选中的列表没有为false, 有就为true
      item.checked = false
      state.selected.forEach((i) => {
        if (i.dietCode == item.dietCode) {
          item.checked = true
        }
      })
    })
    // 保存搜索历史记录
    if (state.searchHistory.indexOf(e) == -1) {
      if (state.searchHistory.length >= 10) {
        state.searchHistory.pop()
      }
      state.searchHistory.unshift(e)
    }
    uni.setStorageSync('searchHistory', JSON.stringify(state.searchHistory))
  })
}, 1000)
const historySelect = (val) => {
  state.searchValue = val
  searchFood(state.searchValue)
}

const typeSelect = (index) => {
  state.active = index
  state.detailList = state.typeList[state.active].list
  state.detailList.forEach((item) => {
    state.selected.forEach((i) => {
      if (i.dietCode == item.dietCode) {
        item.checked = true
      }
    })
  })
  // 解决view层不同步问题，返回顶部
  scrollTop.value = oldScrollTop.value
  nextTick(() => {
    scrollTop.value = 0
  })
}
const scrollTo = (e) => {
  oldScrollTop.value = e.detail.scrollTop
}
const foodAdd = (item: any, type: string) => {
  state.addType = type
  item.amount = 100
  state.addFood = item
  state.setShow = true
  setTimeout(() => {
    // 解决弹窗打开时，input无法获取焦点问题
    state.tipFocus = true
  }, 100)
}
const foodSelect = throttle(() => {
  if (!state.addFood.amount || state.addFood.amount == '0') {
    uni.showToast({
      title: '重量不能为0或空!',
      icon: 'error'
    })
    return
  }
  state.detailList.forEach((item) => {
    if (item.dietCode == state.addFood.dietCode) {
      item.checked = true
    }
  })
  if (state.addType === 'search') {
    state.searchList.forEach((item) => {
      if (item.dietCode == state.addFood.dietCode) {
        item.checked = true
      }
    })
  }
  state.selected.push(state.addFood)
  state.setShow = false
  state.tipFocus = false
}, 300)
const onKey = (e) => {
  const sys = uni.getSystemInfoSync()
  // 自定义弹出键盘事件
  if (e.detail.height) {
    state.bottomHeight = e.detail.height * 2 - sys.safeAreaInsets.bottom * 2 - 36
  } else {
    state.bottomHeight = 0
  }
}
const onInput = (e) => {
  if (e.detail.value * 1 > 3000) {
    state.addFood.amount = 3000
  }
}

const close = () => {
  state.setShow = false
  state.tipFocus = false
  state.bottomHeight = 0
}
const deleteFood = (item, index) => {
  state.selected.splice(index, 1)
  state.typeList.forEach((i) => {
    i.list.forEach((j) => {
      if (j.dietCode === item.dietCode) {
        j.checked = false
      }
    })
  })
}
const finish = () => {
  state.selected.forEach((item) => {
    item.empi = state.userInfo.empi
    item.dietDate = state.date
    item.dietType = state.type
  })
  save_food(state.selected).then((res) => {
    uni.navigateBack({
      delta: 1
    })
  })
}
</script>

<style lang="scss" scoped>
.wrap {
  .search {
    background: #fff;
  }

  .search_content {
    height: calc(100vh - 152rpx);
    padding: 20rpx 0;
    background: #fff;

    .search_history {
      margin: 0 32rpx;

      .history_top {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20rpx;

        .title {
          font-size: 30rpx;
          font-weight: 500;
          color: #333;
        }

        .img_del {
          width: 40rpx;
          height: 40rpx;
          font-size: 40rpx;
          color: #999;
        }
      }

      .history_content {
        display: flex;
        flex-wrap: wrap;
        gap: 20rpx;
        justify-content: flex-start;

        .history_item {
          padding: 10rpx 30rpx;
          font-size: 26rpx;
          font-weight: 400;
          color: #666;
          background: #fafafa;
          border-radius: 30rpx;
        }
      }
    }

    .nodata {
      text-align: center;

      .img_nodata {
        width: 320rpx;
        height: 240rpx;
        margin-top: 222rpx;
      }

      .nodata_text {
        font-size: 28rpx;
        font-weight: 400;
        color: #666;
      }
    }

    .search_list {
      height: calc(100vh - 152rpx);
      overflow: auto;
      background: #fff;

      .search_item {
        position: relative;
        box-sizing: border-box;
        height: 160rpx;
        padding: 34rpx 32rpx;
        border-bottom: 1rpx solid #e5e6eb;

        .name {
          margin-bottom: 10rpx;
          font-size: 30rpx;
          font-weight: 500;
          color: #222;
        }

        .power {
          font-size: 28rpx;
          font-weight: 400;
          color: #666;
        }

        .img_right {
          position: absolute;
          top: 50%;
          right: 32rpx;
          width: 40rpx;
          height: 40rpx;
          margin-top: -20rpx;
        }
      }
    }
  }

  .content {
    display: flex;
    height: calc(100vh - 256rpx - env(safe-area-inset-bottom));
    border-top: 1rpx solid #e5e6eb;

    .left {
      width: 244rpx;
      overflow: auto;

      .item {
        position: relative;
        height: 100rpx;
        padding-left: 32rpx;
        font-size: 32rpx;
        font-weight: 700;
        line-height: 100rpx;
        background: #fafafa;
        border-bottom: 1rpx solid #fff;

        &:nth-last-child(1) {
          border-bottom: 0rpx solid #fff;
        }

        &.on {
          color: #00d1b6;
          background: #fff;
        }

        .line {
          position: absolute;
          top: 50%;
          left: 0;
          width: 12rpx;
          height: 32rpx;
          margin-top: -16rpx;
          background: #00d1b6;
          border-radius: 0 4rpx;
        }
      }
    }

    .scroll-Y {
      height: calc(100vh - 256rpx - env(safe-area-inset-bottom));
    }

    .right {
      flex: 1;
      //   overflow: auto;
      background: #fff;

      .item {
        position: relative;
        box-sizing: border-box;
        height: 160rpx;
        padding: 34rpx 32rpx;
        border-bottom: 1rpx solid #e5e6eb;

        .name {
          margin-bottom: 10rpx;
          font-size: 30rpx;
          font-weight: 500;
          color: #222;
        }

        .power {
          font-size: 28rpx;
          font-weight: 400;
          color: #666;
        }

        .img_right {
          position: absolute;
          top: 50%;
          right: 32rpx;
          width: 40rpx;
          height: 40rpx;
          margin-top: -20rpx;
        }
      }
    }
  }

  .fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 99999;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 12rpx 40rpx;
    padding-bottom: calc(30rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
    background: #fff;
    border-top: 1rpx solid #e5e6eb;

    .fixed_left {
      display: flex;
      align-items: center;
      justify-content: flex-start;

      .img_type {
        width: 48rpx;
        height: 48rpx;
        font-size: 48rpx;
        color: #00d1b6;
        transform: translateY(6rpx);
      }

      .text {
        margin: 0 12rpx;
        font-size: 30rpx;
        font-weight: 500;
        color: #222;
      }

      .img_arrow {
        width: 32rpx;
        height: 32rpx;
        font-size: 32rpx;
        color: #b8bbbd;
        transform: translateY(2rpx);
      }

      .img_up {
        transform: rotateX(180deg);
      }
    }

    .fixed_btn {
      width: 280rpx;
      height: 88rpx;
      margin: 0;
      font-size: 32rpx;
      font-weight: 500;
      line-height: 88rpx;
      color: #fff;
      background: #00d1b6;
      border-radius: 44rpx;
    }

    .disabled {
      background: #ccc;
    }
  }

  .u-popup {
    // 设置重量弹窗
    .food_info {
      padding: 0 32rpx;

      .title {
        width: 100%;
        height: 104rpx;
        font-size: 30rpx;
        font-weight: 500;
        line-height: 104rpx;
        color: #333;
        text-align: center;
      }

      .info_top {
        .name {
          margin-bottom: 10rpx;
          font-size: 30rpx;
          font-weight: 500;
          color: #222;
        }

        .power {
          font-size: 28rpx;
          font-weight: 400;
          color: #666;
        }
      }

      .info_detail {
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        padding: 20rpx 0;
        margin: 26rpx 0 30rpx;
        font-size: 24rpx;
        font-weight: 400;
        color: #999;
        border-top: 1rpx solid #e5e6eb;
        border-bottom: 1rpx solid #e5e6eb;

        .detail_item {
          flex: 1;
          text-align: center;

          .text {
            margin-bottom: 10rpx;
          }
        }
      }

      .input_info {
        position: relative;
        text-align: center;

        .weight_input {
          width: 200rpx;
          height: 84rpx;
          margin: 0 auto;
          font-size: 60rpx;
          font-weight: 500;
          color: #1cd7ae;
          border-bottom: 4rpx solid #1cd7ae;
        }

        .unit {
          position: absolute;
          top: 0;
          right: 235rpx;
          font-size: 24rpx;
          font-weight: 500;
          color: #1cd7ae;
        }

        .hot {
          margin-top: 16rpx;
          font-size: 24rpx;
          font-weight: 400;
          color: #666;
        }
      }

      .submit {
        width: 100%;
        height: 88rpx;
        padding: 0 !important;
        margin: 76rpx 0 32rpx;
        font-size: 32rpx !important;
        font-weight: 500;
        line-height: 88rpx !important;
        color: #fff;
        background: #00d1b6;
        border-radius: 50rpx;
      }
    }
    // 查看已选
    .total {
      margin: 34rpx 32rpx 24rpx;
      font-size: 24rpx;
      font-weight: 400;
      color: #666;
    }

    .lists {
      max-height: 700rpx;
      padding: 0 32rpx 32rpx;
      overflow: auto;

      .item {
        position: relative;
        box-sizing: border-box;
        height: 118rpx;
        margin: 24rpx 0;
        border-bottom: 1rpx solid #e5e6eb;

        .name {
          margin-bottom: 10rpx;
          font-size: 32rpx;
          font-weight: 500;
          color: #222;
        }

        .power {
          font-size: 28rpx;
          font-weight: 400;
          color: #666;
        }

        .img_del {
          position: absolute;
          top: 50%;
          right: 0;
          width: 40rpx;
          height: 40rpx;
          margin-top: -20rpx;
          font-size: 40rpx;
          color: #999;
        }

        &:first-child {
          margin-top: 0;
        }
      }
    }
  }

  ::v-deep .uni-searchbar {
    padding: 24rpx 32rpx;
  }

  ::v-deep .uni-searchbar__text-placeholder {
    font-size: 30rpx !important;
    color: #999 !important;
  }

  ::v-deep .uni-searchbar__box {
    justify-content: flex-start;
    height: 80rpx !important;
    padding: 20rpx 24rpx !important;
    background: #fafafa !important;
    border-radius: 40rpx !important;
  }

  ::v-deep .uni-searchbar__box-search-input {
    font-size: 30rpx !important;
  }

  ::v-deep .uni-searchbar__cancel {
    font-size: 30rpx !important;
    font-weight: 500;
    line-height: 80rpx !important;
    color: #00d1b6 !important;
  }

  ::v-deep .u-icon__icon {
    font-size: 32rpx !important;
    line-height: 50rpx !important;
  }

  ::v-deep .u-loading-icon {
    // 加载logo
    position: absolute;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
